package name.fowler.refactoring.simplestore.reporter.impl;

import name.fowler.refactoring.simplestore.Customer;
import name.fowler.refactoring.simplestore.Movie;
import name.fowler.refactoring.simplestore.PriceCalculator;
import name.fowler.refactoring.simplestore.PriceCalculatorNotFoundException;
import name.fowler.refactoring.simplestore.PriceCalculatorStore;
import name.fowler.refactoring.simplestore.Rental;
import name.fowler.refactoring.simplestore.reporter.IReporter;
import name.fowler.refactoring.simplestore.reporter.report.Cell;
import name.fowler.refactoring.simplestore.reporter.report.Row;
import name.fowler.refactoring.simplestore.reporter.report.Table;

public class CustomerReporter implements IReporter {

	private Customer m_customer;
	
	public Customer getM_customer() {
		return m_customer;
	}
	
	public void setM_customer(Customer m_customer) {
		this.m_customer = m_customer;
	}
	
	public CustomerReporter(Customer customer) {
		setM_customer(customer);
	}
	
	@Override
	public CustomerReport createReport() {
		// TODO Auto-generated method stub

		CustomerReport report = new CustomerReport();
		
		double totalAmount = 0;
		int frequentRenterPoints = 0;
		
		report.setHeader(SimpleStoreReporterHelper.createOneStringTable("Customer report"));
		StringBuilder titleStr = new StringBuilder("Rental record for ");
		titleStr.append(m_customer.getName());
		report.setTitle(SimpleStoreReporterHelper.createOneStringTable(titleStr.toString()));
		
		Table body = new Table();
		
		for(Rental each: m_customer.getRentals()) {
			try {
				
				Movie movie = each.getMovie();
				PriceCalculator calc = PriceCalculatorStore.getInstance().find(movie.getCategory());
				double thisAmount = calc.calculatePrice(each.getDaysRented());
				frequentRenterPoints += calc.calculateBonuses(each.getDaysRented());
			// Show figures for this rental
				Cell movieTitleCell = new Cell(each.getMovie().getTitle());
				Row bodyRow = new Row();
				bodyRow.add(movieTitleCell);
				Cell amountCell = new Cell(thisAmount);
				bodyRow.add(amountCell);
				body.add(bodyRow);
				totalAmount += thisAmount;
			} catch (PriceCalculatorNotFoundException e) {
				e.printStackTrace();
				body = SimpleStoreReporterHelper.createOneStringTable(e.toString());
			}
		}

		report.setBody(body);
		
		// Add footer lines
		Table footer = new Table();
		Row footerRow1 = new Row();
		footerRow1.add(new Cell("Amount owed is"));
		footerRow1.add(new Cell(totalAmount));
		footer.add(footerRow1);
		Row footerRow2 = new Row();
		footerRow2.add(new Cell("You earned"));
		footerRow2.add(new Cell(frequentRenterPoints));
		footerRow2.add(new Cell("frequent renter points."));
		footer.add(footerRow2);
		report.setFooter(footer);
		
		return report;

	}

}
